package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sms.service.OpaSmsService;
import com.budwk.app.sqfw.dto.FireHiddenPeersMsgDTO;
import com.budwk.app.sqfw.dto.SqfwFormSummaryWithFlowDTO;
import com.budwk.app.sqfw.dto.SqfwSummaryPdfExcelCollForAdminDTO;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormSummaryService;
import com.budwk.app.sqfw.services.SqfwSummaryForAdminService;
import com.budwk.app.sqfw.services.impl.SqfwSummaryForAdminServiceImpl;
import com.budwk.app.sqfw.vo.HouseSurveyFormPlaceVO;
import com.budwk.app.sqfw.vo.Sqfw_formSummaryForAdminVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeForAdminUtils;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: SqfwDaYingLuForAdminController
 * @description: 大营安全排查（后台管理系统）
 * @author: LJT
 * @create: 2023-10-11 10:20
 **/
@IocBean
@At("/platform/sqfw/forAdmin")
@ApiDefinition(tag = "大营安全排查")
@Slf4j
public class SqfwDaYingLuForAdminController {

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private OpaSmsService opaSmsService;

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "获取详情")
    @ApiResponses
    @SLog(tag = "获取详情", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> detail(@Param("id") String id) {
        Sqfw_formSummary fetch = sqfwFormSummaryService.fetch(id);
        return Result.success(fetch);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除表数据")
    @SLog(tag = "删除表数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> delete(@Param("id") String id) {
        Sqfw_formSummary sqfwFormSummary = sqfwFormSummaryService.fetch(id);
        if (sqfwFormSummary == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwCompleteflowService.deleteAndUpdateWO(sqfwFormSummary.getSqfwFlowId());
        return Result.success();
    }

    @At("/generateFireHiddenPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成消防隐患排查表PDF 所有单位通用")
    @SLog(tag = "生成消防隐患排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateFireHiddenPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        log.info("dayinglu generateFireHiddenPdf param: {}", JSONObject.toJSONString(formSummaryWithFlow));
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.generateFireHiddenPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    @At("/retryGenerateFireHiddenPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成消防隐患排查表PDF")
    @SLog(tag = "重新生成消防隐患排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateFireHiddenPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.retryGenerateFireHiddenPdf(userId, sqfwFlowId);
        return Result.success();
    }

    @At("/retryGenerateFireHiddenPdfForAdmin")
    @Ok("json")
    @GET
    @ApiOperation(name = "重新生成消防隐患排查表PDF 用于临时生成")
    @SLog(tag = "重新生成消防隐患排查表PDF 用于临时生成")
    public Result<?> retryGenerateFireHiddenPdfForAdmin(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwFormSummaryService.retryGenerateFireHiddenPdf(userId, sqfwFlowId);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/generateFireHiddenExcelForApp")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成消防隐患排查表Excel合集")
    @SLog(tag = "生成消防隐患排查表Excel", value = "${args[0]},${args[1]},,${args[2]}")
    @SaCheckLogin
    public Result<?> generateFireHiddenCollectionExcelForApp(@Param("sqfwId") String sqfwId, @Param("workOrderId") String workOrderId, @Param("fileIndex") Integer fileIndex) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateFireHiddenCollectionExcelForApp("", sqfwId, workOrderId, userId, fileIndex);
        if (StringUtils.isBlank(excelUrl)) return Result.error("暂无数据，不能生成Excel");
        return Result.data(excelUrl);
    }

    @At("/sendFireHiddenPeersMsg")
    @Ok("json")
    @POST
    @ApiOperation(name = "发送同行人员短信消息")
    @SLog(tag = "发送同行人员短信消息", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> sendFireHiddenPeersMsg(@Param("..") FireHiddenPeersMsgDTO dto) {
        int sendCount = sqfwSummaryForAdminService.sendFireHiddenPeersMsg(dto);
        if (sendCount <= 0) return Result.error("发送失败");
        return Result.success();
    }

    /**
     * 供小程序使用
     *
     * @return 返回url
     */
    @At("/generateFormSummaryPdfConverge")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成Pdf合集")
    @SLog(tag = "生成Pdf合集", value = "${args[0]},${args[1]},,${args[2]}")
    @SaCheckLogin
    public Result<?> generateFormSummaryPdfConverge(@Param("sqfwId") String sqfwId, @Param("workOrderId") String workOrderId, @Param("fileType") String fileType) {
        String pdfUrl = sqfwSummaryForAdminService.generateFormSummaryPdfConverge(sqfwId, workOrderId, fileType);
        if (StringUtils.isBlank(pdfUrl)) return Result.error("该任务下没有排查单");
        return Result.data(pdfUrl);
    }

    //-----------------------------------------------------------------------------------------
    //   垃圾分类调查表相关接口
    //-----------------------------------------------------------------------------------------
    @At("/generateRefuseClassifyPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成垃圾分类PDF")
    @SLog(tag = "生成垃圾分类PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateRefuseClassifyPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.generateRefuseClassifyPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/generateRefuseClassifyExcelForApp")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成垃圾分类排查表Excel")
    @SLog(tag = "生成垃圾分类排查表Excel", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateRefuseClassifyExcelForApp(@Param("sqfwId") String sqfwId) {
        String excelUrl = sqfwSummaryForAdminService.generateRefuseClassifyExcelForApp(sqfwId);
        if (StringUtils.isBlank(excelUrl)) return Result.error();
        return Result.data(excelUrl);
    }

    @At("/retryGenerateRefuseClassifyPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新生成垃圾分类排查表PDF")
    @SLog(tag = "重新生成垃圾分类排查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateRefuseClassifyPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.retryGenerateRefuseClassifyPdf(userId, sqfwFlowId);
        return Result.success();
    }

    // ----------------------------------------------------------------------------------------------
    // 生成入户调查表
    // ----------------------------------------------------------------------------------------------
    @At("/listPlaceForHouseSurveyFrom")
    @Ok("json")
    @POST
    @ApiOperation(name = "入户调查查询地点")
    @SLog(tag = "入户调查查询地点", value = "${args[0]},${args[1]},${args[2]},${args[3]}")
    @SaCheckLogin
    public Result<?> listPlaceForHouseSurveyFrom(@Param("unitId") String unitId, @Param("workOrderId") String workOrderId, @Param("a5") String a5, @Param("a4") String a4) {
        String userId = SecurityUtil.getUserId();
        List<HouseSurveyFormPlaceVO> list = sqfwSummaryForAdminService.listPlaceForHouseSurveyFrom(unitId, workOrderId, userId, a5, a4);
        return Result.success(list);
    }

    @At("/generateHouseSurveyFormPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "生成入户调查PDF")
    @SLog(tag = "生成入户调查PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateHouseSurveyFormPdf(@Param("..") SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.generateHouseSurveyFormPdf(userId, formSummaryWithFlow);
        return Result.success();
    }

    /**
     * 供小程序使用，无权限，只需要登陆即可
     *
     * @return 返回url
     */
    @At("/getDownloadHouseSurveyFormExcelType")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取能够生成excel的种类")
    @SLog(tag = "获取能够生成excel的种类", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> getDownloadHouseSurveyFormExcelType(@Param("sqfwId") String sqfwId) {
        List<String> excelTypeList = sqfwSummaryForAdminService.getDownloadHouseSurveyFormExcelType(sqfwId);
        return Result.data(excelTypeList);
    }


    @At("/retryGenerateHouseSurveyFormPdf")
    @Ok("json")
    @POST
    @ApiOperation(name = "重新入户调查表PDF")
    @SLog(tag = "重新入户调查表PDF", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> retryGenerateHouseSurveyFormPdf(@Param("sqfwFlowId") String sqfwFlowId) {
        String userId = SecurityUtil.getUserId();
        sqfwSummaryForAdminService.retryGenerateHouseSurveyFormPdf(userId, sqfwFlowId);
        return Result.success();
    }

    @At("/listSecondHouseSurvey")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id需要二次入户调查的数据")
    @SLog(tag = "根据服务记录id需要二次入户调查的数据", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> listSecondHouseSurvey(@Param("sqfwId") String sqfwId) {
        String userId = SecurityUtil.getUserId();
        List<HouseSurveyFormPlaceVO> list = sqfwSummaryForAdminService.listSecondHouseSurvey(sqfwId, userId);
        return Result.data(list);
    }


    //--------------------------------------------------------------------------------------------
    //  根据服务记录id数组合并excel和pdf
    //--------------------------------------------------------------------------------------------
    @At("/generateServiceRecordPdfCollForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集")
    @SLog(tag = "根据服务记录id数组生成pdf合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfColl(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList) {
        String pdfUrl = sqfwSummaryForAdminService.generateServiceRecordPdfColl(conditionList);
        return Result.data(pdfUrl);
    }

    @At("/generateServiceRecordExcelColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成Excel合集")
    @SLog(tag = "根据服务记录id数组生成Excel合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelColl(@Param("conditionList") List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList, @Param("fileIndex") Integer fileIndex, @Param("excelType") String excelType) {
        if (conditionList.size() <= 0) {
            return Result.error("数据不存在！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateCheckRecordExcelColl("", conditionList, userId, fileIndex, excelType);
        return Result.data(excelUrl);
    }

    /**
     * 后台管理系统任务列表查询（用于后台管理系统）
     * Add by LJT 2023-10-10
     */
    @At("/listSummaryForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "后台管理系统任务列表查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @ApiResponses(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "后台管理系统任务列表查询", value = "${args[0]}}")
    @SaCheckLogin
    public Result<?> listSummaryForBM(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
        return this.sqfwSummaryForAdminService.listSummaryDYLForBM(bean,pageNo,pageSize,pageOrderName,pageOrderBy);
    }

    /**
     * 勾选下载，后台管理系统任务下载excel集合（用于后台管理系统）
     * Add by LJT 2023-10-10
     */
    @At("/generateServiceRecordExcelCollForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id和汇总Id数组生成Excel合集")
    @SLog(tag = "根据服务记录id数组和汇总Id生成Excel合集", value = "${args[0]},${args[1]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollForBM(
            @Param("sumIdList") List<String> sumIdList,
            @Param("fileType") String fileType,
            @Param("fileIndex") Integer fileIndex) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceRecordExcelCollForBM("", sumIdList, userId, fileType, fileIndex);
        return Result.data(excelUrl);
    }

    /**
     * 后台管理系统任务下载excel集合压缩包（用于后台管理系统）
     * Add by LJT 2023-10-16
     */
    @At("/generateServiceRecordExcelCollZipForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id和汇总Id数组生成Excel合集")
    @ApiFormParams(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "根据服务记录id数组和汇总Id生成Excel合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollZipForBM(@Param("..") Sqfw_formSummaryForAdminVO bean, @Param("fileIndexList") List<Integer> fileIndexList) {
        List<String> sumIdList = sqfwSummaryForAdminService.getDaYingLuExcelFileDownSumIdList(bean);
        if (sumIdList.size() <= 0) {
            return Result.error("未查询到数据！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceSummaryExcelCollZipForBM("", bean.getCounty(), sumIdList, userId, fileIndexList, "");
        if(StringUtils.isNotEmpty(excelUrl) && excelUrl.contains("https://xyoss.obs.cn-hcsoysgz1.hcsoysgz.gzdata.com.cn")) {
            excelUrl = excelUrl.replace("https://xyoss.obs.cn-hcsoysgz1.hcsoysgz.gzdata.com.cn:443", "https://f.xyasst.com/myhuaweicloud/");
        }
        if (null == excelUrl) {
            return Result.error("未查询到数据！");
        }
        return Result.data(excelUrl);
    }

    /**
     * 后台管理系统任务下载pdf集合压缩包（用于后台管理系统）
     * Add by LJT 2023-10-17
     */
    @At("/generateServiceRecordPdfCollZipForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集zip")
    @ApiFormParams(
            implementation = Sqfw_formSummaryForAdminVO.class
    )
    @SLog(tag = "根据服务记录id数组生成pdf合集zip", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfCollZipForBM(@Param("..") Sqfw_formSummaryForAdminVO bean) {
        List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList = sqfwSummaryForAdminService.getDaYingLuPdfFileDownSumIdList(bean);
        String pdfUrl = sqfwSummaryForAdminService.generateServiceRecordPdfColl(conditionList);
        return Result.data(pdfUrl);
    }
}
